<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>watchIsAutoPlay</title>
</head>

<body>
    <audio src="https://www.eveningwater.com/static/resouces/audio/1.mp3" id="audio"></audio>
    <div id="content"></div>
    <script>
        /**
        * 方法1
        * @param el 
        * @returns 
        */
        // const watchIsAutoPlay = (el) => {
        //         if (!(el instanceof HTMLAudioElement)) {
        //     throw new Error('el must be a HTMLAudioElement');
        // }
        //     el.muted = true;
        //     return Promise.resolve(el.play()).then(() => true).catch(() => false)
        // }
        /**
         * 方法2
         * @param el 
         * @returns 
         */
        const watchIsAutoPlay = (el) => {
            if (!(el instanceof HTMLAudioElement)) {
                throw new Error('el must be a HTMLAudioElement');
            }
            const src = el.getAttribute('src');
            if (!src) {
                return Promise.resolve(false);
            }
            return new Promise((resolve) => {
                const a = new Audio();
                a.autoplay = true;
                a.muted = true;
                a.addEventListener('play', () => resolve(true))
                a.src = src;
                resolve(false);
            });
        }
        const audio = document.getElementById('audio');
        const content = document.getElementById('content');
        window.onload = async () => {
            const isAutoPlay = await watchIsAutoPlay(audio);
            content.innerHTML = `当前${isAutoPlay ? '支持' : '不支持'}自动播放音频`;
        };
    </script>
</body>

</html>